/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.logging.Level;
import java.util.logging.Logger;


/**
 *
 * @author Peewhy
 */
public class ServerConfig {
    // Default params
    public static final int     DEFAULT_PORT = 8080;
    public static final int     DEFAULT_SHUTDOWN_PORT = 80;
    public static final String  DEFAULT_ROOT_CATALOG = "."; //."/home/peewhy/workspace/Webmail";
    public static final String  DEFAULT_CONTENT_TYPE = "text/html";
    public static final Level     DEFAULT_LOG_LEVEL = Level.SEVERE;
    public static final String     DEFAULT_FILENAME = "index.html";  
    
    // Other params
    public static final String     COMMENT_MARK = "#";   
    public static final String     PARAM_SPLITTER = ":";   
    public static final String     CONFIG_DIR = ""; //"/config/";   
    public static final String     PARAM_PORT = "port";
    public static final String     PARAM_LOCATION = "location";
    private Queue<String> indexFiles;
    
   private int port;
   private int shutdownPort;
   private Level level;   
   private String root;
   Logger logger;

   public ServerConfig() {
       port = DEFAULT_PORT;
       shutdownPort = DEFAULT_SHUTDOWN_PORT;       
       root = DEFAULT_ROOT_CATALOG;  
       level = DEFAULT_LOG_LEVEL;
       logger = Logger.getLogger(Server.LOG);
       createIndexQueue();
   }
   
   public Iterator<String> getIndexIterator(){
       return indexFiles.iterator();
   }
   
   /**
    * returns root catalog for webserver files
    * @return root catalog
    */
   public String getRoot() {
       return root;
   }
   
   /**
    * returns port number, on which webserver is currently working
    * @return port number
    */
   public int getPort() {
       return port;
   }
   
   /**
    * returns recommended level for logging of application
    * @return level of logging
    */
   public Level getLevel(){
       return level;
   }
   
   /**
    * Loads configuration from specified file
    * @param f configuration file to be loaded
    * @throws java.io.IOException if given file is not available
    */
   public void loadFromFile(String f) throws IOException {
        String nname = getRoot() + ServerConfig.CONFIG_DIR + f;
        logger.info("Loading configuration file from: " + nname);
        BufferedReader in = new BufferedReader(new FileReader(nname));
        String str;
        while ((str = in.readLine()) != null) {
            String n = str.trim();
            if (n.startsWith(ServerConfig.COMMENT_MARK)) {
                // Comment ignored                
            }
            else {
                try {
                    String[] ar = n.split(ServerConfig.PARAM_SPLITTER);
                    String argument = ar[0].trim().toLowerCase();
                    String val = ar[1].trim();                    
                    
                    if (argument.equals(ServerConfig.PARAM_PORT)) {
                    	this.port = Integer.parseInt(val);
                    	logger.info("Load port number from configuration: " + this.port);
                    }
                    else if (argument.equals(ServerConfig.PARAM_LOCATION)) {
                    	this.root = val;
                    	logger.info("Load serving location (path) from configuration: " + this.root);
                    }
                    else {
                    	logger.log(Level.INFO, "Configuration parameter unrecognized: " + argument);
                    }
                    
                }
                catch (IndexOutOfBoundsException ioo) {
                    logger.log(Level.FINEST, "Config file line corrupted");
                }
                catch (Exception e) {
                	logger.log(Level.INFO, "Error handling configuration file line");
                }
            }
        }
        in.close();
   }

   // Creates priority list for index files: index.html, index.php ...
    private void createIndexQueue() {
        indexFiles = new LinkedList<String>();
        indexFiles.add("index.html");
        indexFiles.add("index.htm");
        indexFiles.add("content.html");
        indexFiles.add("content.htm");
    }
}
